import 'package:dio/dio.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show kIsWeb;

class ProfilePage extends StatefulWidget {
   ProfilePage({super.key, required this.userInfo});

  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}





class _ProfilePageState extends State<ProfilePage> {


  //  Map userInfo = {
  //   "avatar": "",
  //   "nickName": "",
  // };

Map _userInfo = {};

  final TextEditingController _avatarController = TextEditingController();

  // 控制器获取用户名
  final TextEditingController _controller = TextEditingController();

// 从相机或相册中选择图片
selectAvatar() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 200,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {},
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    _pickImageFromGallery();
                  },
                  
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('AI相册'),
                  onTap: () {
                    // _pickImageFromGallery();
                  },
                  
                )
              ]));
        });
  }


  Future<void> _pickImageFromGallery() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    print(pickedFile);
    if (pickedFile != null) {
      try {
        FormData formData;
        
        // 根据平台使用不同的方式创建 FormData
        if (kIsWeb) {
          // Web 平台处理方式
          final bytes = await pickedFile.readAsBytes();
          formData = FormData.fromMap({
            "file": MultipartFile.fromBytes(
              bytes,
              filename: pickedFile.name,
            ),
            "type": "avatar",
          });
        } else {
          // 移动平台处理方式
          formData = FormData.fromMap({
            "file": await MultipartFile.fromFile(pickedFile.path),
            "type": "avatar",
          });
        }
        
        var res = await http.post('/upload', formData);
        if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
        setState(() {
          _userInfo['avatar'] = res['data']['url'];
        });
      } finally {
        Navigator.pop(context);
      }
    }
  }


// 更新昵称  ai写的
// _updateNickName() async {
//     var res = await http.post('/user/update', {
//       'nickName': _controller.text
//     });
//     if (res['code']!= 10000) return ToastUtil.showError('更新昵称失败!');
//     ToastUtil.showSuccess('更新昵称成功!');
//     setState(() {
//       _userInfo['nickName'] = _controller.text;
//     });
// }

// 更新昵称
_updateNickName() async {
    if (_controller.text.isEmpty) {
      return ToastUtil.showError('昵称不能为空!');
    }
    try {
      await http.put('/userInfo', {"nickName": _controller.text});
      setState(() {
        _userInfo['nickName'] = _controller.text;
        ToastUtil.showSuccess('修改成功!');
        eventBus.fire(RefreshMine());
        Navigator.pop(context);
      });
    } catch (e) {
      return ToastUtil.showError('网络异常!');
    }
}

    @override
    void initState() {
      super.initState();
      setState(() {
        _userInfo = widget.userInfo;
        // _avatarController.text = userInfo['nickName'];
        _controller.text = _userInfo['nickName'];
      });
    }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
            GestureDetector(
              onTap: () {
                selectAvatar();
              },
              child:         ClipRRect(
                      borderRadius: BorderRadius.circular(50.0),
                    //   child: Image.asset(
                    //     'images/avatar_1.jpg',
                    //     width: 30,
                    //     height: 30,
                    //   ),
                    // ),

                    child: _userInfo['avatar'] != ''
                            ? Image.network(_userInfo['avatar'],
                                width: 30, height: 30)
                            : Image.asset('images/avatar_1.jpg',
                                width: 30, height: 30)),
            ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
           Row(
            children: [
              Text('昵称'),
              Spacer(),
              Expanded(
                child: TextField(
                  controller: _controller,
                  decoration: InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                  onEditingComplete: (){
                    _updateNickName();
                  },
                ),
              ),
              Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
